package com.lw.lwte.autoweb.base;

import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.concurrent.TimeUnit;

public class BasePage{
    private WebDriver driver;
    long timeout = 10;
    long iwait = 10;
    public BasePage() {
        // 初始化driver-始终只有一个对象
        if (driver == null) {

            String env = System.getenv("CHROME_HOME");
            // 设置ChromeDriver的路径，环境变量需要配置为 CHROME_HOME
            System.setProperty("webdriver.chrome.driver", env);
            driver = new ChromeDriver();

            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
            driver.manage().timeouts().pageLoadTimeout(5, TimeUnit.SECONDS);
            driver.manage().window().maximize();
            // 初始化页面元素
            PageFactory.initElements(driver, this);
        }
    }



    public void click(By locator, int timeout) {
        WebDriverWait wait = new WebDriverWait(driver, timeout);
        WebElement ele = wait.until(ExpectedConditions.elementToBeClickable(locator));
        ele.click();
    }

    public void inputText(String text, By locator) {
        WebDriverWait wait = new WebDriverWait(driver, iwait);
        WebElement ele = wait.until(ExpectedConditions.presenceOfElementLocated(locator));
        Actions actions = new Actions(driver);
            actions.click(ele)
                    .keyDown(Keys.CONTROL)
                    .sendKeys("a")
                    .keyDown(Keys.DELETE)
                    .build()
                    .perform();
//            actions.clear();
        actions.sendKeys(ele, text).build().perform();
    }



    /**
     * 关闭浏览器
     *
     * 如果浏览器实例（driver）不为空，则关闭浏览器并释放资源，将浏览器实例置为空
     */
    public void closeBrowser() {
        if (driver != null) {
            driver.quit();
            driver = null;
        }
    }

    /**
     * 导航到指定的URL
     *
     * @param url 要导航到的URL地址
     */
    public void toUrl(String url) {
        driver.get(url);
    }

    public void captureScreenshot(String filePath) {
        File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        try {
            // 将截图文件保存到指定路径
            Files.copy(screenshot.toPath(), Paths.get(filePath), StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}